package com.lotso.web.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: GlobalExceptionAdvice
 * Description: 全局异常处理器
 * Date: 2018/8/30 10:51 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String error() {
        return "/error/500";
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String notFound() {
        return "/error/404";
    }


    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String, Object> exception(Exception ex) {
        Map<String, Object> map = new HashMap<>();
        // 根据不同错误获取错误信息
        if (ex instanceof AbstractException) {
            map.put("code", ((AbstractException) ex).getCode());
            map.put("msg", ex.getMessage());
        } else {
            String message = ex.getMessage();
            map.put("code", 500);
            map.put("msg", message == null || message.trim().isEmpty() ? "系统异常，联系管理员" : message);
            map.put("details", message);
        }
        log.error(ex.getMessage(), ex);
        return map;
    }

}
